package l5;

import java.util.EmptyStackException;

public class ArrayStack<T> implements Stack<T> {
    private static final int DEFAULT_CAPACITY = 10;
    private Object[] elements;
    private int top;

    public ArrayStack() {
        this(DEFAULT_CAPACITY);
    }

    public ArrayStack(int initialCapacity) {
        if (initialCapacity <= 0){
            throw new IllegalArgumentException("初始大小必须为正数" + initialCapacity);
        }
        this.elements = new Object[initialCapacity];
        this.top = -1;
    }

    @Override
    public boolean isEmpty() {
        return top == -1;
    }

    @Override
    public int size() {
        return top+1;
    }

    @Override
    public T pop() {
        if (isEmpty()){
            throw new EmptyStackException();
        }
        return (T) elements[top--];
    }

    @Override
    public void push(T t) {
        if (top == elements.length-1){
            ensureCapacity();
        }
        elements[++top] = t;
    }

    private void ensureCapacity() {
        int newCapacity = elements.length * 2;
        Object[] newElements = new Object[newCapacity];
        System.arraycopy(elements, 0, newElements, 0, elements.length);
        elements = newElements;
    }

    @Override
    public T peek() {
        if (isEmpty()){
            throw new EmptyStackException();
        }
        return (T) elements[top];
    }

    @Override
    public void clear() {
        top=-1;
    }
}
